﻿using Prism.Ioc;
using Prism.Mvvm;
using ProcessControl.Model;
using System;
using System.Collections.ObjectModel;
using System.Windows.Threading;

namespace ProcessControl.ViewModels
{
    public class DisplayDataViewModel : BindableBase
    {
        Dispatcher dispatcher;
        public DisplayDataViewModel(IContainerExtension container)
        {
            dispatcher = Dispatcher.CurrentDispatcher;
            datas = new ObservableCollection<ProductionData>();
        }

        private ObservableCollection<ProductionData> datas;
        public ObservableCollection<ProductionData> Datas
        { 
            get { return datas; } 
            set { datas = value; }
        }

        //使用事件聚合器滚动更新 UI线程 外部线程
        public void DataShift(ProductionData data)
        {
            try
            {
                if (data == null) { return; }
                //更新ObservableCollection集合必须使用Dispatcher
                dispatcher.BeginInvoke(
                new Action(() =>
                {
                    Datas.Insert(0, data);
                    //获取最后一个元素的索引
                    int lastIndex = Datas.Count - 1;
                    //索引大于等于11就移除最后一个
                    if (lastIndex >= 32)
                        Datas.RemoveAt(lastIndex);
                }));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
    }
}
